package org.xwb.springcloud.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.xwb.springcloud.constant.MqDeadLetterConstant;

/**
 * @author Administrator
 */
@Configuration
public class RabbitmqDeadLetterConfig {

    /**
     * 死信队列
     */
    @Bean
    public Queue deadLetterQueue() {
        return new Queue(MqDeadLetterConstant.DEAD_LETTER_QUEUE, true);
    }

    /**
     * 死信交换机
     */
    @Bean
    public DirectExchange deadLetterExchange() {
        return new DirectExchange(MqDeadLetterConstant.DEAD_LETTER_EXCHANGE);
    }

    // 将死信队列绑定到死信交换机，并设置路由键与死信队列的路由键一致
    @Bean
    public Binding bindingDeadLetter() {
        // 绑定死信队列到死信交换机和路由键一致
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()).with(MqDeadLetterConstant.DEAD_LETTER_ROUTING_KEY);
    }

    //todo =======================业务队列、交换机配置========================

    /**
     * 定义业务队列
     * todo  配置业务队列，并设置死信交换机、死信队列、TTL、路由键等信息
     */
    @Bean
    public Queue businessQueue() {
        //业务的队列
        return QueueBuilder.durable(MqDeadLetterConstant.BUSINESS_QUEUE)
                //设置死信交换机（DLX），当消息无法被业务消费时（例如过期、拒绝等），消息会被转发到指定的死信交换机
                .deadLetterExchange(MqDeadLetterConstant.DEAD_LETTER_EXCHANGE)
                //设置死信队列的路由键，用于将消息正确地路由到死信队列中
                .deadLetterRoutingKey(MqDeadLetterConstant.DEAD_LETTER_ROUTING_KEY)
                // 可选：设置消息过期时间
                .ttl(10000)
                .build();
    }
    /**
     * 业务队列 交换机
     */
    @Bean
    public DirectExchange ackBusinessExchange() {
        return new DirectExchange(MqDeadLetterConstant.BUSINESS_EXCHANGE);
    }

    /**
     * 将业务队列绑定到业务交换机上，指定交换机的路由
     */
    @Bean
    public Binding bindingBusiness() {
        return BindingBuilder.bind(businessQueue()).to(ackBusinessExchange()).with(MqDeadLetterConstant.BUSINESS_ROUTING_KEY);
    }


}